﻿using System;
using System.Web.Mvc;
using ASPItalia.ModelVirtualCasting.Common;
using ASPItalia.ModelVirtualCasting.Web.Models;

namespace ASPItalia.ModelVirtualCasting.Web.Filters
{
    public class ShowModelsAttribute : ActionFilterAttribute
    {
        public int Number { get; set; }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            var model = filterContext.Controller.ViewData.Model as IHasModels;

            if (model == null)
            {
                throw new InvalidOperationException(
                    "Impossibile usare ShowNews se il model non implementa IHasModels");
            }

            IModelRepository modelRepository = ApplicationContext.Current.Models;
            model.Models.Clear();
            model.Models.AddRange(modelRepository.GetRandomModels(this.Number));
        }
    }
}